package com.madrivergroup.mamatodo.adapter;

import java.util.ArrayList;
import java.util.List;

import com.madrivergroup.mamatodo.R;
import com.madrivergroup.mamatodo.tasks.Task;
import com.madrivergroup.mamatodo.views.TaskListItem;


import static com.madrivergroup.mamatodo.util.MaMaConstants.*;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

/**
 * 
 * @author peterdelaney
 *
 * Adapther for the list of Tasks to perform in the ViewTaskActivity 
 * 
 */
public class TaskListAdapter extends BaseAdapter {

	public static String NAME = TaskListAdapter.class.getSimpleName();
	
	private List<Task> listOfTasks = new ArrayList<Task>();
	private Context   context = null;
	
	
	public TaskListAdapter(List<Task> list, Context context) {
		super();		
		Log.d(LOG, NAME + ":TaskListAdapter( list, context )");
		
		this.listOfTasks = list;
		this.context = context;
	}
	public TaskListAdapter(Context context, AttributeSet set ) {
		super();
		Log.d(LOG, NAME + ":TaskListAdapter( context, set )");		
		this.context = context;
	}

	public void setTaskList(List<Task> l ) {
		Log.d(LOG, NAME + ":setTaskList() size :" + l.size() );
		listOfTasks.clear();
		listOfTasks = l;
	}
	
	
	public int getCount() {
		Log.d(LOG, NAME + ":getCount() return =" + listOfTasks.size() );		
		return listOfTasks.size();
	}

	public Object getItem(int num) {
		Log.d(LOG, NAME + ":getItem( " + num + " )");
		return listOfTasks.get(num);
	}

	public long getItemId(int position) {
		Log.d(LOG, NAME + ":getItemId( " + position + " )");		
		return position;
	}

	/**
	 * Returns the current View or TaskListItem based on the position
	 * 
	 */
	public View getView(int position, View convertView, ViewGroup parent) {
		Log.d(LOG, NAME + ":getView( " + position + ", view, parent )");
		
		TaskListItem item = null;
		if( null == convertView ) {
		   item = (TaskListItem)View.inflate(context, R.layout.task_list_item, null );
		}
		else {
		   item = (TaskListItem)convertView;
		}
		item.setTask( listOfTasks.get( position ) );
		return item;
	}

	/** 
	 * Convience method that allows the Application for redraw the UI
	 */
	public void forceReload() {
		Log.d(LOG, NAME + ":forceReload()");
		/**
		Task temp = new Task("TEST");
		temp.setId( listOfTasks.size() + 1);
		listOfTasks.add(temp);
		**/
		notifyDataSetChanged();
	}
	
	/**
	 * Remove any task from the List that is completed
	 */
	public List<Task> removeCompletedTasks() {
		Log.d(LOG, NAME + ":removeCompletedTasks()");
		
		List<Task> removalList = new ArrayList<Task>();
		for( Task t : listOfTasks ) {
			if( t.isComplete() ) {
				removalList.add( t );
			}
		}
		
		// Remove From List that the TaskListAdapter users to view
		listOfTasks.removeAll( removalList );

		return removalList;
	} // end of removeCompletedTasks()

} // end of TaskListAdapter class
